<?php

namespace App\Console\Commands;

use App\Product;
use Carbon\Carbon;
use Illuminate\Console\Command;

class PointcardQueue extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pointcard:queue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'pointcard queue';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $date = Carbon::now()->format('Y-m-d');

        //计算平台当日收益
        $money = Product::where('created_at', 'like', $date)->sum('value');
        
        $this->queue($money);

    }

    /**
     * @function 筛选可激活的积分卡
     *
     * @param $money
     * @return mixed
     */
    public function queue($money)
    {
        $first = \App\PointCardQueue::join('point_card', 'point_card.id', '=', 'point_card_queue.card_id')
            ->select('profit', 'price', 'point_card_queue.user_id')
            ->where('point_card_queue.status', 0)
            ->first();

        if ($money > $first->profit) {
            $first->status = 1; //积分卡状态修改为等待激活
            $first->save();

            $money = $money - $first->profit;
            return $this->queue($money);
        }

        return $money;
    }

}
